<?php

namespace App\Repositories;

use App\Enums\FinancialEnum;
use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use App\Models\MainDB\UserWithdraw;
use App\Services\Tools\FinancialService;
use Illuminate\Support\Facades\Log;
use App\Services\Tools\CommonService;
use Illuminate\Support\Facades\Hash;

//引入hash
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

use function Clue\StreamFilter\fun;

class UserWithdrawRepository
{
    /**
     * 总提现金额
     *
     * @param $param
     * @return bool
     */
    public function userWithdraw($param)
    {
        $result = app('model_user_withdraw')->where('status', 2)->whereBetween('add_time', [$param['start_time'], $param['end_time']]);
        if (!empty($param['grade']) && empty($param['keyword'])) {
            $user_rank = app('model_user')->where('rank_id', $param['grade'])->pluck('user_id')->toArray();
            $arr_uids = $user_rank;
        }
        if (!empty($param['keyword']) && empty($param['grade'])) {
            $user_data = app('model_user_data')->where('nickname', 'like', "%{$param['keyword']}%")->orWhere('user_code', 'like', "%{$param['keyword']}%")->pluck('user_id')->toArray();
            $user = app('model_user')->where('mobile', 'like', "%{$param['keyword']}%")->pluck('user_id')->toArray();
            $arr_uids = array_values(array_unique(array_merge($user_data, $user)));
        }

        if (!empty($param['keyword']) && !empty($param['grade'])) {
            $user_data_ids = app('model_user_data')->where('nickname', 'like', "%{$param['keyword']}%")->orWhere('user_code', 'like', "%{$param['keyword']}%")->select('user_id')->pluck('user_id')->toArray();
            $user_rank_ids = app('model_user')->where('rank_id', $param['grade'])->pluck('user_id')->toArray();
            $user_data = array_values(array_intersect($user_data_ids, $user_rank_ids));
            $user = app('model_user')->where('mobile', 'like', "%{$param['keyword']}%")->where('rank_id', $param['grade'])->pluck('user_id')->toArray();
            $arr_uids = array_values(array_unique(array_merge($user_data, $user)));
        }

        if (isset($arr_uids)) {
            $result = $result->where(function ($query) use ($arr_uids) {
                $query->whereIn('user_id', $arr_uids);
            });
        }
        $result = $result->select(DB::raw('sum(money) as  new_money'), 'user_id')->first()->toArray();
        $result = $result['new_money'] ?? 0;

        return $result;
    }

    /**
     * 审核
     */
    public function batchCheck($idArr, $type, $remark)
    {
        DB::connection("mysql")->transaction(function () use ($idArr, $type, $remark) {
            //获取提现信息
            $list = app("model_user_withdraw")->whereIn("id", $idArr)->get();
            foreach ($list as $info) {
                if ($info->platform_status != 1 || $info->status != 1) {
                    throw new BasicException(1001,'选中的列表中有已经操作过的订单，请刷新重试');
                }
                if ($type == 1) { //同意
                    //改变订单状态
                    $result = $info->editStatus(2);

                    if ($result) {
                        //更新资金日志
//                        app('model_account_earnings_log')->where([
//                            ["source_id", "=", $info->id],
//                            ["change_type", "=", 23],
//                        ])->update([
//                            'change_desc' => '提现已到账',
//                            'change_type' => 2,
//                        ]);
                    } else {
                        throw new BasicException(10001, "操作失败！");
                    }
                }
                if ($type == 2) { //拒绝
                    //改变订单状态
                    $result = $info->editStatus(3,$remark);
                    if ($result) {

                        app('repo_account')->change($info->user_id, 24, abs($info->gold), "已退回", $info->id);

                        //删除待提现资金日志
                        app('model_account_earnings_log')->where([
                            ["source_id", "=", $info->id],
                            ["change_type", "=", 23],
                        ])->delete();

                    } else {
                        throw new BasicException(10001, "操作失败！");
                    }
                    //给用户发送提现失败消息
                    $bankText = $this->getBankTypeText($info->bank_type);
                    $msg = "您在".date('m月d日H:i',$info->add_time)."发起的提现，提现失败。提现方式：".$bankText."提现。";
                    //给用户发送提现成功消息
                    app('repo_user_news')->userNewsAdd([
                        'user_id'  => $info->user_id,
                        'content'  => $msg,
                        'add_time' => time(),
                        'title'    => '提现通知',
                    ]);
//                    //减去冻结金额
//                    $result1 = app('repo_user')->serUserEarnings($info->user_id, $info->gold, 1);
//                    if ($result && $result1) {
//                        //更新资金日志
//                        app('model_account_earnings_log')->where([
//                            ["source_id", "=", $info->id],
//                            ["change_type", "=", 23],
//                        ])->update([
//                            'change_desc' => '已退回',
//                            'change_type' => 24,
//                        ]);
//                    } else {
//                        throw new BasicException(10001, "操作失败！");
//                    }
                }
            }
        }, 5);
        // 推送到财务系统 financialSys
        $ids = implode(',',$idArr);
        $this->pushWithdrawDataToFinancialSys($ids);
        return true;
    }

    /**
     * 设置备注
     */
    public function setRemark($id, $param)
    {
        $remark = $param['remark'];

        $obj = app('model_user_withdraw')->where("id", $id)->first();
        if (!$obj) {
            throw new BasicException(10001, "id不合法！");
        }

        $obj->remark = $remark;

        $obj->save();
        // 推送到财务系统 financialSys
        $this->pushWithdrawDataToFinancialSys($id);
        return true;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getAliWithDrawQueryList(array $params)
    {

        $bankType = isset($params['bank_type']) ? $params['bank_type'] : 0;
        $type = isset($params['type']) ? $params['type'] : 0;
        $remark = isset($params['remark']) ? $params['remark'] : "";
        $mobile = isset($params['mobile']) ? $params['mobile'] : "";
        $bankNum = isset($params['bank_num']) ? $params['bank_num'] : "";
        $realName = isset($params['real_name']) ? $params['real_name'] : "";
        $userCode = isset($params['user_code']) ? $params['user_code'] : 0;
        $status = isset($params['status']) ? $params['status'] : 0;
        $platformStatus = isset($params['platform_status']) ? $params['platform_status'] : 0;
        $startTime = isset($params['start_time']) ? strtotime($params['start_time']) : 0;
        $endTime = isset($params['end_time']) ? strtotime($params['end_time'] . " 23:59:59") : 0;
        $cardNumber = isset($params['card_number']) ? $params['card_number'] : "";
        $auditStartTime = isset($params['audit_start_time']) ? strtotime($params['audit_start_time']) : 0;
        $auditEndTime = isset($params['audit_end_time']) ? strtotime($params['audit_end_time']) : 0;
        $operateStartTime = isset($params['operate_start_time']) ? strtotime($params['operate_start_time']) : 0;
        $operateEndTime = isset($params['operate_end_time']) ? strtotime($params['operate_end_time']) : 0;
        $whereArr = [];
        if ($startTime) {
            $whereArr[] = ["t1.add_time", ">=", $startTime];
        }

        if ($endTime) {
            $whereArr[] = ["t1.add_time", "<=", $endTime];
        }

        if ($status) {
            //如果打款状态是 待打款，则审核状态是通过的情况
            if ($status == UserWithdraw::PAYMENT_STATUS_VERIFY) {
                $whereArr[] = ["t1.platform_status", "=", UserWithdraw::CHECK_STATUS_PASS];
            }
            $whereArr[] = ["t1.status", "=", $status];
        }

        if ($platformStatus) {
            $whereArr[] = ["t1.platform_status", "=", $platformStatus];
        }

        if ($userCode) {
            $whereArr[] = ["t2.user_code", "=", $userCode];
        }

        if ($realName) {
            $whereArr[] = ["t1.cardholder", "like", "%" . $realName . "%"];
        }

        if ($bankNum) {
            $whereArr[] = ["t1.bank_num", "=", $bankNum];
        }

        if ($remark) {
            $whereArr[] = ["t1.remark", "like", "%" . $remark . "%"];
        }

        if ($type) {
            $whereArr[] = ["t1.type", "=", $type];
        }

        if ($bankType) {
            $whereArr[] = ['t1.bank_type', "=", $bankType];
        }

        if ($cardNumber) {
            $whereArr[] = ["t3.card_number", "=", $cardNumber];
        }
        if (!empty($auditStartTime)){
            $whereArr[] = ["t1.audit_time", ">=", $auditStartTime];
        }
        if (!empty($auditEndTime)){
            $whereArr[] = ["t1.audit_time", "<=", $auditEndTime];
        }
        if (!empty($operateStartTime)){
            $whereArr[] = ["t1.operate_time", ">=", $operateStartTime];
        }
        if (!empty($operateEndTime)){
            $whereArr[] = ["t1.operate_time", "<=", $operateEndTime];
        }
        $whereFunc = [];
        if(!empty($mobile)) {
            $whereFunc = function ($query) use ($mobile) {
                $query->where('t3.mobile', 'like', "%" . $mobile . "%")
                      ->orWhere('t4.mobile', 'like', "%" . $mobile . "%");
            };
        }

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];
        $withDrawModel = app('model_user_withdraw');
        $userDataModel = app('model_user_data');
        $userBankModel = app('model_user_bank');
        $userModel = app('model_user');
//        $childS=app('model_user_auth')->select('user_id','id_number')->where('app_status',1)->groupBy('user_id');

        $select = [
            "t1.id",
            "t2.user_code",
            "t1.money",
            "t1.money_fee",
            "t1.fee_rate",
            "t1.cardholder",
            "t1.bank_num",
            "t1.add_time",
            "t1.audit_time",
            "t1.type",
            "t1.status",
            "t1.platform_status",
            "t1.remark",
            "t1.mobile as tmobile",
            "t1.mobile",
            DB::raw("t4.mobile as origin_mobile"),
            "t1.bank_name",
            "t1.bank_zhi",
            "t1.card_number",
            "t1.card_number as id_number",
            "t1.bank_type",
            "t1.money_total",
            "t1.mobile as user_mobile",
            "t1.remark_batch",
            't1.operate_time',
            't1.update_time',
            't1.fail_reason'
        ];
        $result = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);


        foreach ($result as $item) {
            $item->gold = $item->money * 100;
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
            $item->audit_time = empty($item->audit_time) ? "" : date("Y-m-d H:i:s", $item->audit_time);
            $item->operate_time = empty($item->operate_time) ? "" : date("Y-m-d H:i:s", $item->operate_time);
            $item->update_time = empty($item->update_time) ? "" : date("Y-m-d H:i:s", $item->update_time);
            $item->id_number = empty($item->id_number) ? "" : $item->id_number . ' ';
            $item->tmobile = empty($item->tmobile) ? "" : $item->tmobile . ' ';
            //支付宝账号,身份证号,手机号需要脱敏处理
            $item->new_bank_num = strReplaces($item->bank_num, 3,4,'*');
            $item->new_card_number = strReplaces($item->card_number, 6,8,'*');
            $item->new_mobile = strReplaces($item->mobile, 3,4,'*');
        }

        $select1 = [
            "t1.platform_status",
            "t1.status",
            "t1.money",
            "t1.id",
        ];
        $total = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select1)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->get();

        return [
            'lists' => $result,
            'stat'  => $this->calcTitle($total),
        ];
    }

    /**
     * 计算头部统计
     * @param $withDraws
     * @return array
     */
    public function calcTitle($withDraws)
    {
        //运营待审核金额
        $applyMoney = 0;
        $applyCount = 0;
        //运营拒绝金额
        $auditRefuseMoney = 0;
        $auditRefuseCount = 0;
        //财务待打款金额
        $auditPassMoney = 0;
        $auditPassCount = 0;
        //财务拒绝金额
        $financeRefuseMoney = 0;
        $financeRefuseCount = 0;
        //财务打款金额
        $financePassMoney = 0;
        $financePassCount = 0;
        foreach ($withDraws as $w) {
            if ($w->platform_status == 1 && $w->status == 1) {
                $applyMoney  = bcadd($applyMoney,$w->money,2);
                $applyCount++;
            }
            if ($w->platform_status == 3) {
                $auditRefuseMoney = bcadd($auditRefuseMoney,$w->money,2);
                $auditRefuseCount++;
            }
            if ($w->platform_status == 2 && $w->status == 1 ) {
                $auditPassMoney = bcadd($auditPassMoney,$w->money,2);
                $auditPassCount++;
            }
            if ($w->status == 3) {
                $financeRefuseMoney = bcadd($financeRefuseMoney,$w->money,2);
                $financeRefuseCount++;
            }
            if ($w->platform_status == 2 && $w->status == 2 ) {
                $financePassMoney = bcadd($financePassMoney,$w->money,2);
                $financePassCount++;
            }
        }
        return [
            'apply_money'   =>  bcadd($applyMoney,0,2),
            'apply_count'   =>  $applyCount,
            'audit_refuse_money' => bcadd($auditRefuseMoney,0,2),
            'audit_refuse_count' => $auditRefuseCount,
            'audit_pass_money'  =>  bcadd($auditPassMoney,0,2),
            'audit_pass_count'  =>  $auditPassCount,
            'finance_refuse_money'=>bcadd($financeRefuseMoney,0,2),
            'finance_refuse_count'=>$financeRefuseCount,
            'finance_pass_money' => bcadd($financePassMoney,0,2),
            'finance_pass_count' => $financePassCount,
        ];
    }

    /**
     * 获取用户提现记录
     * @param $params array 数组参数 开始时间 结束时间 页数 步长 id 多id
     * @return array
     * @author yangwenjie
     * @date 2022/4/2
     */
    public function getFinancialWithdrawsList($params)
    {
        $withDrawModel = app('model_user_withdraw');
        // 五表联查 financialSys
        $field = implode(',', [
            'uw.id as app_withdraw_id', 'uw.bank_type as type', 'uw.bank_num',
            'uw.money', 'uw.money_total', 'uw.gold', 'uw.audit_time','uw.bank_name','uw.bank_zhi','uw.fail_reason',
            'uw.status', 'uw.remark', 'uw.platform_status as audit_status',
            'uw.user_id', 'ud.user_code', 'ud.nickname', 'uw.cardholder as truename',
            'uw.card_number as id_card',
            'uw.mobile',
            'uw.add_time',
        ]);
        $query = $withDrawModel
            ->selectRaw($field)
            ->from('ln_user_withdraw as uw')
            ->leftJoin('ln_user_data as ud', 'ud.user_id', 'uw.user_id')
//            ->leftJoin('ln_user_auth as ua', 'ua.user_id', 'uw.user_id')
            ->leftJoin('ln_user as u', 'u.user_id', 'uw.user_id');
        $where = [];
//        $where['ua.app_status'] = 1;
        if (!empty($params['id'])) {
            $where['uw.id'] = $params['id'];
        }
        if (!empty($params['ids'])) {
            $query->whereIn('uw.id', $params['ids']);
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $query->whereBetween('uw.add_time', [strtotime($params['start_time']), strtotime($params['end_time'])]);
        }
        $query->where($where);
        if (!empty($params['page']) && !empty($params['page_size'])) {
            $query->paginate($params['page_size'], [], '', $params['page']);
        }

        $list =  $query->orderBy('uw.id','asc')->get()->toArray();
        if (!empty($list)) {

            $list = array_column($list, null, 'app_withdraw_id');
            $list = array_values($list);

            foreach ($list as $k => $v) {
                $list[$k]['created_from'] = 1;

                //金额从元转为分
                $list[$k]['money'] *= 100;
                $list[$k]['fee'] = $list[$k]['money_total'] * 100 - $list[$k]['money'];
                unset($list[$k]['money_total']);

                //申请提现时间
                $list[$k]['apply_time'] = date("Y-m-d H:i:s", $v['add_time']);
                unset($list[$k]['add_time']);

                //备注不能为null
                if (empty($v['remark'])) {
                    $list[$k]['remark'] = "";
                }

                //支付宝账号
                $list[$k]['alipay_account'] = "";
                if ($v['type'] == 1) {
                    $list[$k]['alipay_account'] = $v['bank_num'];
                }

                //审核时间
                if ($v['audit_time'] != 0) {
                    $list[$k]['audit_time'] = date("Y-m-d H:i:s", $v['audit_time']);
                } else {
                    $list[$k]['audit_time'] = "0000-00-00 00:00:00";
                }

                if ($v['type'] == FinancialEnum::BANKCARD_WITHDRAW){
                    $list[$k]['bank_card_no']   = $v['bank_num'];
                    $list[$k]['bank_name']      = $v['bank_name'];
                    $list[$k]['contact']        = $v['mobile'];
                    $list[$k]['opening_address']= $v['bank_zhi'];
                }
                if ($v['type'] == FinancialEnum::COMPANY_WITHDRAW){
                    $list[$k]['bank_card_no']   = $v['bank_num'];
                    $list[$k]['bank_name']      = $v['bank_name'];
                    $list[$k]['contact']        = $v['mobile'];
                    $list[$k]['opening_address']= $v['bank_zhi'];
                    $list[$k]['corporate_name'] = $v['truename'];
                }

                //null全部转空字符串
                foreach ($v as $k2=>$v2){
                    if (is_null($v2)){
                        $list[$k][$k2]="";
                    }
                }

                //审核状态 字段映射
                //对接文档中字段含义  打款状态:1-待打款;2-打款成功;3-打款审核拒绝
                //对接文档中字段含义 audit_status：  审核状态:0-待审核;1-审核通过
                // 配合财务系统的状态维护 新增状态需要配合修改
                if (in_array($v['audit_status'],[1,2,3])) {
                    if ($v['audit_status'] == UserWithdraw::CHECK_STATUS_REFUSE) {
                        $list[$k]['status'] = $v['audit_status'];
                    }

                    // 财务系统转换
                    $list[$k]['audit_status'] = $v['audit_status'] - 1;
                } else{
                    //异常情况返回值，避免之后加字段，造成数据状态错乱
                    $list[$k]['status'] = 1;
                    $list[$k]['audit_status'] = 0;
                }

            }
        }
        return $list;
    }

    //financialSys 推送提现信息到财务系统
    public function pushWithdrawDataToFinancialSys($ids)
    {
        $ids = explode(',',$ids);
        $params = [
            'ids' => $ids
        ];
        $list = $this->getFinancialWithdrawsList($params);
        if (!empty($list)) {
            (new FinancialService())->syncWithdrawData($list);
        }
        return true;
    }

    /**
     * 自动审核提现订单
     */
    public function autoCheckWithdrawOrder()
    {
        $key = sprintf(RedisKeyEnum::AUTO_ZFB_RECHARGE_ORDER, 1);
        // 判断是否开启自动审核状态
        $isAuto = app('redis')->get($key);
        if ($isAuto) {
            // 查询内部账号信息
            $insiderIds = app('model_insider_user')
                ->pluck('user_id')
                ->toArray();
            dd($insiderIds);
        }
    }

    /**
     * @Desc:银行卡提现列表
     * @param  array  $params
     * @return mixed
     * @author: shiquan
     * @Time: 2022/9/29 16:46
     */
    public function getBankWithDrawQueryList(array $params)
    {
        $bankType = isset($params['bank_type']) ? $params['bank_type'] : 3;
        $type = isset($params['type']) ? $params['type'] : 0;
        $mobile = isset($params['mobile']) ? $params['mobile'] : "";
        $bankNum = isset($params['bank_num']) ? $params['bank_num'] : "";
        $realName = isset($params['cardholder']) ? $params['cardholder'] : "";
        $userCode = isset($params['user_code']) ? $params['user_code'] : 0;
        $status = isset($params['status']) ? $params['status'] : 0;
        $platformStatus = isset($params['platform_status']) ? $params['platform_status'] : 0;
        $startTime = isset($params['start_time']) ? strtotime($params['start_time']) : 0;
        $endTime = isset($params['end_time']) ? strtotime($params['end_time'] . " 23:59:59") : 0;
        $cardNumber = isset($params['card_number']) ? $params['card_number'] : '';
        $auditStartTime = isset($params['audit_start_time']) ? strtotime($params['audit_start_time']) : 0;
        $auditEndTime = isset($params['audit_end_time']) ? strtotime($params['audit_end_time'] . " 23:59:59") : 0;
        $operateStartTime = isset($params['operate_start_time']) ? strtotime($params['operate_start_time']) : 0;
        $operateEndTime = isset($params['operate_end_time']) ? strtotime($params['operate_end_time'] . " 23:59:59") : 0;

        $whereArr = [];
        if ($startTime) {
            $whereArr[] = ["t1.add_time", ">=", $startTime];
        }

        if ($endTime) {
            $whereArr[] = ["t1.add_time", "<=", $endTime];
        }

        if ($status) {
            //如果打款状态是 待打款，则审核状态是通过的情况
            if ($status == UserWithdraw::PAYMENT_STATUS_VERIFY) {
                $whereArr[] = ["t1.platform_status", "=", UserWithdraw::CHECK_STATUS_PASS];
            }
            $whereArr[] = ["t1.status", "=", $status];
        }

        if ($platformStatus) {
            $whereArr[] = ["t1.platform_status", "=", $platformStatus];
        }

        if ($cardNumber) {
            $whereArr[] = ["t1.card_number", "=", $cardNumber];
        }

        if ($userCode) {
            $whereArr[] = ["t2.user_code", "=", $userCode];
        }

        if ($realName) {
            $whereArr[] = ["t1.cardholder", "like", "%" . $realName . "%"];
        }

        if ($bankNum) {
            $whereArr[] = ["t1.bank_num", "=", $bankNum];
        }

        if ($type) {
            $whereArr[] = ["t1.type", "=", $type];
        }

        if ($bankType) {
            $whereArr[] = ['t1.bank_type', "=", $bankType];
        }
        if (!empty($auditStartTime)){
            $whereArr[] = ["t1.audit_time", ">=", $auditStartTime];
        }
        if (!empty($auditEndTime)){
            $whereArr[] = ["t1.audit_time", "<=", $auditEndTime];
        }
        if (!empty($operateStartTime)){
            $whereArr[] = ["t1.operate_time", ">=", $operateStartTime];
        }
        if (!empty($operateEndTime)){
            $whereArr[] = ["t1.operate_time", "<=", $operateEndTime];
        }

        $whereFunc = function ($query) use ($mobile) {
            if (!empty($mobile)) {
                $query->where('t3.mobile', 'like', "%" . $mobile . "%")
                    ->orWhere('t4.mobile', 'like', "%" . $mobile . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['page_size']) ? 10 : $params['page_size'];
        $withDrawModel = app('model_user_withdraw');
        $userDataModel = app('model_user_data');
        $userBankModel = app('model_user_bank');
        $userModel = app('model_user');
        //        $childS=app('model_user_auth')->select('user_id','id_number')->where('app_status',1)->groupBy('user_id');
        $select = [
            "t1.id",
            "t1.user_id",
            "t2.user_code",
            "t1.money",
            "t1.money_fee",
            "t1.fee_rate",
            "t1.cardholder",
            "t1.bank_num",
            "t1.add_time",
            "t1.audit_time",
            "t1.type",
            "t1.status",
            "t1.platform_status",
            "t1.remark",
            "t1.mobile as tmobile",
            "t1.mobile",
            DB::raw("t4.mobile as origin_mobile"),
            "t1.bank_name",
            "t1.bank_zhi",
            "t1.card_number",
            "t1.card_number as id_number",
            "t1.bank_type",
            "t1.money_total",
            "t1.mobile as user_mobile",
            "t1.fail_reason",
            't2.nickname',
            't1.gold',
            "t1.remark_batch",
            't1.operate_time',
            't1.update_time',
        ];
        $result = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);

        $ids = array_column($result->toArray()['data'] ?? [],'user_id');
        //获取本月的时间的时间戳
        $year = date('Y');
        $month = date('m');
        $startTime = strtotime($year.'-'.$month.'-01'.' 00:00:00');
        if (in_array($month,['01','03','05','07','08','10','12'])){
            $endTime = strtotime($year.'-'.$month.'-31'.' 23:59:59') + 1;
        } else {
            $endTime = strtotime($year.'-'.$month.'-30'.' 23:59:59') + 1;
        }
        $currenMonth = app('model_user_withdraw')->selectRaw('user_id, SUM(money_total) as money_total')
            ->where(['bank_type' => 3, 'status' => UserWithdraw::CHECK_STATUS_PASS])
            ->whereIn('user_id', $ids)
            ->whereBetween('operate_time', [$startTime, $endTime])
            ->groupBy('user_id')->get()->toArray();
        $newUsersMoney = array_column($currenMonth, 'money_total','user_id');

        foreach ($result as $item) {
            //$item->gold = $item->gold;
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
            $item->audit_time = empty($item->audit_time) ? "" : date("Y-m-d H:i:s", $item->audit_time);
            $item->operate_time = empty($item->operate_time) ? "" : date("Y-m-d H:i:s", $item->operate_time);
            $item->update_time = empty($item->update_time) ? "" : date("Y-m-d H:i:s", $item->update_time);
            $item->id_number = empty($item->id_number) ? "" : $item->id_number . ' ';
            $item->tmobile = empty($item->tmobile) ? "" : $item->tmobile . ' ';
            $item->currenMonthMoney = $newUsersMoney[$item['user_id']] ?? 0;
            //身份证号,手机号需要脱敏处理
            $item->new_card_number = strReplaces($item->card_number, 6,8,'*');
            $item->new_mobile = strReplaces($item->mobile, 3,4,'*');
        }

        $total = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->get();

        return [
            'lists'     =>  $result,
            'stat'      =>  $this->calcTitle($total),
        ];
    }

    /**
     * @Desc:对公打款提现列表
     * @param  array  $params
     * @return mixed
     * @author: shiquan
     * @Time: 2022/9/30 16:46
     */
    public function getCorporateWithDrawQueryList(array $params)
    {
        $bankType = isset($params['bank_type']) ? $params['bank_type'] : 4;
        $type = isset($params['type']) ? $params['type'] : 0;
        $mobile = isset($params['mobile']) ? $params['mobile'] : "";
        $bankNum = isset($params['bank_num']) ? $params['bank_num'] : "";
        $realName = isset($params['cardholder']) ? $params['cardholder'] : "";
        $userCode = isset($params['user_code']) ? $params['user_code'] : 0;
        $status = isset($params['status']) ? $params['status'] : 0;
        $platformStatus = isset($params['platform_status']) ? $params['platform_status'] : 0;
        $startTime = isset($params['start_time']) ? strtotime($params['start_time']) : 0;
        $endTime = isset($params['end_time']) ? strtotime($params['end_time'] . " 23:59:59") : 0;
        $cardNumber = isset($params['card_number']) ? $params['card_number'] : '';
        $auditStartTime = isset($params['audit_start_time']) ? strtotime($params['audit_start_time']) : 0;
        $auditEndTime = isset($params['audit_end_time']) ? strtotime($params['audit_end_time']) : 0;
        $operateStartTime = isset($params['operate_start_time']) ? strtotime($params['operate_start_time']) : 0;
        $operateEndTime = isset($params['operate_end_time']) ? strtotime($params['operate_end_time']) : 0;

        $whereArr = [];
        if ($startTime) {
            $whereArr[] = ["t1.add_time", ">=", $startTime];
        }

        if ($endTime) {
            $whereArr[] = ["t1.add_time", "<=", $endTime];
        }

        if ($status) {
            //如果打款状态是 待打款，则审核状态是通过的情况
            if ($status == UserWithdraw::PAYMENT_STATUS_VERIFY) {
                $whereArr[] = ["t1.platform_status", "=", UserWithdraw::CHECK_STATUS_PASS];
            }
            $whereArr[] = ["t1.status", "=", $status];
        }

        if ($platformStatus) {
            $whereArr[] = ["t1.platform_status", "=", $platformStatus];
        }

        if ($cardNumber) {
            $whereArr[] = ["t1.card_number", "=", $cardNumber];
        }

        if ($userCode) {
            $whereArr[] = ["t2.user_code", "=", $userCode];
        }

        if ($realName) {
            $whereArr[] = ["t1.cardholder", "like", "%" . $realName . "%"];
        }

        if ($bankNum) {
            $whereArr[] = ["t1.bank_num", "=", $bankNum];
        }

        if ($type) {
            $whereArr[] = ["t1.type", "=", $type];
        }

        if ($bankType) {
            $whereArr[] = ['t1.bank_type', "=", $bankType];
        }
        if (!empty($auditStartTime)){
            $whereArr[] = ["t1.audit_time", ">=", $auditStartTime];
        }
        if (!empty($auditEndTime)){
            $whereArr[] = ["t1.audit_time", "<=", $auditEndTime];
        }
        if (!empty($operateStartTime)){
            $whereArr[] = ["t1.operate_time", ">=", $operateStartTime];
        }
        if (!empty($operateEndTime)){
            $whereArr[] = ["t1.operate_time", "<=", $operateEndTime];
        }

        $whereFunc = function ($query) use ($mobile) {
            if (!empty($mobile)) {
                $query->where('t3.mobile', 'like', "%" . $mobile . "%")
                    ->orWhere('t4.mobile', 'like', "%" . $mobile . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['page_size']) ? 10 : $params['page_size'];
        $withDrawModel = app('model_user_withdraw');
        $userDataModel = app('model_user_data');
        $userBankModel = app('model_user_bank');
        $userModel = app('model_user');
        //        $childS=app('model_user_auth')->select('user_id','id_number')->where('app_status',1)->groupBy('user_id');

        $select = [
            "t1.id",
            "t1.user_id",
            "t2.user_code",
            "t1.money",
            "t1.money_fee",
            "t1.fee_rate",
            "t1.cardholder",
            "t1.bank_num",
            "t1.add_time",
            "t1.audit_time",
            "t1.type",
            "t1.status",
            "t1.platform_status",
            "t1.remark",
            "t1.mobile as tmobile",
            "t1.mobile",
            DB::raw("t4.mobile as origin_mobile"),
            "t1.bank_name",
            "t1.bank_zhi",
            "t1.card_number",
            "t1.card_number as id_number",
            "t1.bank_type",
            "t1.money_total",
            "t1.mobile as user_mobile",
            "t1.fail_reason",
            't2.nickname',
            't1.gold',
            't1.operate_time',
            't1.update_time',
        ];

        $result = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->orderBy('t1.id', 'desc')->paginate($perPage, ['*'], '', $page);

        $ids = array_column($result->toArray()['data'] ?? [],'user_id');
        //获取本月的时间的时间戳
        $year = date('Y');
        $month = date('m');
        $startTime = strtotime($year.'-'.$month.'-01'.' 00:00:00');
        if (in_array($month,['01','03','05','07','08','10','12'])){
            $endTime = strtotime($year.'-'.$month.'-31'.' 23:59:59') + 1;
        } else {
            $endTime = strtotime($year.'-'.$month.'-30'.' 23:59:59') + 1;
        }
        $currenMonth = app('model_user_withdraw')->selectRaw('user_id, SUM(money_total) as money_total')
            ->where(['bank_type' => 4, 'status' => UserWithdraw::CHECK_STATUS_PASS])
            ->whereIn('user_id', $ids)
            ->whereBetween('audit_time', [$startTime, $endTime])
            ->groupBy('user_id')->get()->toArray();
        $newUsersMoney = array_column($currenMonth, 'money_total','user_id');

        foreach ($result as $item) {
            //$item->gold = $item->money * 100;
            $item->add_time = empty($item->add_time) ? "" : date("Y-m-d H:i:s", $item->add_time);
            $item->audit_time = empty($item->audit_time) ? "" : date("Y-m-d H:i:s", $item->audit_time);
            $item->operate_time = empty($item->operate_time) ? "" : date("Y-m-d H:i:s", $item->operate_time);
            $item->update_time = empty($item->update_time) ? "" : date("Y-m-d H:i:s", $item->update_time);
            $item->id_number = empty($item->id_number) ? "" : $item->id_number . ' ';
            $item->tmobile = empty($item->tmobile) ? "" : $item->tmobile . ' ';
            $item->currenMonthMoney = $newUsersMoney[$item['user_id']] ?? 0;
            //银行卡账号,手机号需要脱敏处理
            $item->new_bank_num = strReplaces($item->bank_num, 4,6,'*');
            $item->new_mobile = strReplaces($item->mobile, 3,4,'*');
        }

        $total = app('model_user_withdraw')
            ->from($withDrawModel->getTable() . " as t1")
            ->select($select)
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userBankModel->getTable() . " as t3"), "t1.bank_id", "=", "t3.id")
            ->leftJoin(DB::raw($userModel->getTable() . " as t4"), "t1.user_id", "=", "t4.user_id")
            ->where($whereArr)
            ->where($whereFunc)
            ->get();
        return [
            'lists'     =>      $result,
            'stat'      =>      $this->calcTitle($total)
        ];
    }

    /**
     * @Desc:批量审核
     * @param $idArr
     * @param $type
     * @param $failReason
     * @return bool
     * @throws \Throwable
     * @author: shiquan
     * @Time: 2022/9/30 11:23
     */
    public function batchBankCheck($idArr, $type, $failReason)
    {
        DB::connection("mysql")->transaction(function () use ($idArr, $type, $failReason) {
            //获取提现信息
            $list = app("model_user_withdraw")->whereIn("id", $idArr)->get();
            foreach ($list as $info) {
                if ($info->platform_status != 1 || $info->status != 1) {
                    throw new BasicException(1001,'选中的列表中有已经操作过的订单，请刷新重试');
                }
                if ($type == 1) { //同意
                    //改变订单状态
                    $result = $info->editBankStatus(2);

                    if ($result) {
                        //更新资金日志
                        //                        app('model_account_earnings_log')->where([
                        //                            ["source_id", "=", $info->id],
                        //                            ["change_type", "=", 23],
                        //                        ])->update([
                        //                            'change_desc' => '提现已到账',
                        //                            'change_type' => 2,
                        //                        ]);
                    } else {
                        throw new BasicException(10001, "操作失败！");
                    }
                }
                if ($type == 2) { //拒绝
                    //改变订单状态
                    $result = $info->editBankStatus(3,$failReason);
                    if ($result) {

                        app('repo_account')->change($info->user_id, 24, abs($info->gold), "已退回", $info->id);

                        //删除待提现资金日志
                        app('model_account_earnings_log')->where([
                            ["source_id", "=", $info->id],
                            ["change_type", "=", 23],
                        ])->delete();

                    } else {
                        throw new BasicException(10001, "操作失败！");
                    }
                    //给用户发送提现失败消息
                    $bankText = $this->getBankTypeText($info->bank_type);
                    $msg = "您在".date('m月d日H:i',$info->add_time)."发起的提现，提现失败。提现方式：".$bankText."提现。";
                    //给用户发送提现成功消息
                    app('repo_user_news')->userNewsAdd([
                        'user_id'  => $info->user_id,
                        'content'  => $msg,
                        'add_time' => time(),
                        'title'    => '提现通知',
                    ]);
                    //                    //减去冻结金额
                    //                    $result1 = app('repo_user')->serUserEarnings($info->user_id, $info->gold, 1);
                    //                    if ($result && $result1) {
                    //                        //更新资金日志
                    //                        app('model_account_earnings_log')->where([
                    //                            ["source_id", "=", $info->id],
                    //                            ["change_type", "=", 23],
                    //                        ])->update([
                    //                            'change_desc' => '已退回',
                    //                            'change_type' => 24,
                    //                        ]);
                    //                    } else {
                    //                        throw new BasicException(10001, "操作失败！");
                    //                    }
                }
            }
        }, 5);
        // 推送到财务系统 financialSys
        if ($type == 1) { //同意
            $ids = implode(',',$idArr);
            $this->pushWithdrawDataToFinancialSys($ids);
        }
        return true;
    }

    /**
     * 获取对应的提现类型文本
     * @param $bankType
     * @return string
     */
    public function getBankTypeText($bankType)
    {
        if ($bankType == FinancialEnum::ALIPAY_WITHDRAW) {
            $source = "支付宝";
        }
        if ($bankType == FinancialEnum::WECHAT_WITHDRAW) {
            $source = "微信";
        }
        if ($bankType == FinancialEnum::BANKCARD_WITHDRAW) {
            $source = "银行卡";
        }
        if ($bankType == FinancialEnum::COMPANY_WITHDRAW) {
            $source = "对公账户";
        }
        return $source;
    }
}
